import User from "../models/User";
import { Request, Response } from "express";
import bcrypt from "bcryptjs";
import svgCaptcha from "svg-captcha";
import { unescape } from "lodash";
// import SMSService from '../services/SMSService'; // 假设您已经有了发送短信的服务
// import VerificationCode from '../models/VerificationCode'; // 验证码模型

// 生成并存储验证码
// const generateAndStoreCode = async (phoneNumber: string) => {
//     const verificationCode = Math.floor(100000 + Math.random() * 900000).toString(); // 生成六位数验证码
//     // 存储验证码到数据库（或其他存储方式）
//     const newCode = new VerificationCode({ phoneNumber, code: verificationCode });
//     await newCode.save();
//     return verificationCode;
// };

// 发送验证码
// export const sendVerificationCode = async (req: Request, res: Response) => {
//     const { phoneNumber } = req.body;
//     try {
//         const code = await generateAndStoreCode(phoneNumber);
//         SMSService.sendSMS(phoneNumber, `您的验证码是: ${code}`);
//         res.status(200).json({ message: '验证码已发送' });
//     } catch (error) {
//         res.status(500).json({ message: error.message });
//     }
// };

// 验证验证码
// const verifyCode = async (phoneNumber: string, code: string) => {
//     const record = await VerificationCode.findOne({ phoneNumber, code });
//     return record !== null;
// };

// 用户注册
// export const registerUser = async (req: Request, res: Response) => {
//     const { phoneNumber, password, verificationCode } = req.body;
//     try {
//         if (!await verifyCode(phoneNumber, verificationCode)) {
//             return res.status(400).json({ message: '无效的验证码' });
//         }

//         const hashedPassword = await bcrypt.hash(password, 10);
//         const newUser = new User({ phoneNumber, password: hashedPassword, isVerified: true });
//         await newUser.save();

//         res.status(201).json({ message: '注册成功', user: newUser });
//     } catch (error) {
//         res.status(500).json({ message: error.message });
//     }
// };

export const generateCaptcha = (req: any, res: Response) => {
    const captcha = svgCaptcha.createMathExpr({
        size: 4, // 验证码长度
        width: 156,
        fontSize: 56,
        noise: 3, // 噪声线条数
        color: true, // 彩色验证码
        // background: "#1ba784", // 背景颜色
        ignoreChars: '0oOliLI'
    });

    // 将验证码文本存储在会话中，用于验证
    req.session = captcha.text.toLocaleLowerCase();
    console.log("session:", captcha.text.toLocaleLowerCase());
    res.cookie("captcha", req.session);

    // 返回验证码图片
    res.type("svg");
    res.send({
        data: {
            code: `data:image/svg+xml;base64,${Buffer.from(captcha.data).toString('base64')}`,
            validCodeReqNo: captcha.text.toLocaleLowerCase(),
        },
    });
};
